import React, { useEffect, useRef, useState } from 'react';
import { Card, Space, Typography, message, Row, Col, Button } from 'antd';
import { quotation } from '@/services/order/order_api';
import { TruckPreOrder } from '../../types';
import dayjs from 'dayjs';
import { cloneDeep, isEqual } from 'lodash';
const { Text } = Typography;
import { cleanAccessorialsNode} from './validator';
import {  useIntl} from "@umijs/max";

interface QuoteInfoProps {
  formData: TruckPreOrder;
  setFormData: (data: any) => void;
  setDataChange: (changed: boolean) => void;
}

const QuoteInfo: React.FC<QuoteInfoProps> = ({ formData, setFormData, setDataChange }) => {
  const intl = useIntl();
  const [loading, setLoading] = useState(false);
  const hasFetchedInitial = useRef(false);
  const [quoteData, setQuoteData] = useState<any[]>([]);
  const [formDataChanged, setFormDataChanged] = useState(false);
  const prevFormDataRef = useRef<TruckPreOrder>();

  const fetchQuotation = async (params: any) => {
    try {
      setLoading(true);
      const response = await quotation(params);      
      if (response.code === 0) {
        setQuoteData(response.data);
        // 如果formData中已有选中的报价，保持选中状态
        if (formData.quote) {
          const updatedData = response.data.map((item: any) => ({
            ...item,
            selected: item.id === formData.quote.id,
          }));
          setQuoteData(updatedData);
          setFormDataChanged(false);
          setDataChange(false);
        }
      } else {
        let errorMsg =
          response.msg || intl.formatMessage({ id: "request.error.create" });               
        message.error(errorMsg);       
        return;
      }
    } catch (error) {
      message.error(intl.formatMessage({ id: "message.quotation.fetchError" }));
      console.error("Fetch quotation error:", error);      
    } finally {
      setLoading(false);
    }
  };


  const isEqualFormData = (pre: TruckPreOrder, current: TruckPreOrder) => {
    // 比较基本字段
    if (
      pre.productCode !== current.productCode ||
      pre.referenceNo !== current.referenceNo ||
      pre.shipperAddressDT !== current.shipperAddressDT ||
      pre.deliveryAddressDT !== current.deliveryAddressDT
    ) {
      return false;
    }

    // 比较boxs数组
    if (pre.boxs.length !== current.boxs.length) {
      return false;
    }

    for (let i = 0; i < pre.boxs.length; i++) {
      const preBox = pre.boxs[i];
      const currentBox = current.boxs[i];

      if (!isEqual(preBox, currentBox)) {
        return false;
      }
    }

    // 比较shipperAddress和deliveryAddress的oaPostcode
    if (
      !isEqual(pre.shipperAddress, current.shipperAddress) ||
      !isEqual(pre.deliveryAddress, current.deliveryAddress)
    ) {
      return false;
    }

    return true;
  };
  useEffect(() => {

    if (prevFormDataRef.current && !isEqualFormData(prevFormDataRef.current, formData)) {
      console.log("params change");
      setFormDataChanged(true);   
      setDataChange(true);   
      setFormData(prev => ({
        ...prev,
        quote: null,
        requote: true,
      }));

    }
    prevFormDataRef.current = cloneDeep(formData);
     if (!hasFetchedInitial.current) {
      hasFetchedInitial.current = true;
      fetchQuotation(formData);      
    }
  }, [formData]);

  // useEffect(() => {
  //   if (!hasFetchedInitial.current) {
  //     hasFetchedInitial.current = true;
  //     fetchQuotation(formData);      
  //   }
  // }, [formData]);

  const handleSelectQuote = (quote: any) => {
    // 如果点击的是已选中的报价，则取消选中；否则选中当前quote
    const newQuote = formData.quote?.id === quote.id ? null : quote;
    setFormData(prev => ({
      ...prev,
      quote: newQuote
    }));

  };
  const handleCleanQuote = () => {
    setFormData(prev => ({
      ...prev,
      quote: null,
      requote: false,
    }));

  };

  const formatDate = (timestamp: number) => {
    return dayjs(timestamp).format('YYYY-MM-DD HH:mm');
  };
  const handleRefreshQuotation = () => {
    cleanAccessorialsNode(formData);
    fetchQuotation(formData);
    setFormDataChanged(false);
    setDataChange(false);
    handleCleanQuote()
  };
  return (
    <div>
      <Card
        title={intl.formatMessage({ id: "pages.quotation.title" })}
        loading={loading}
      >
        <Space direction="vertical" size={12} style={{ width: "100%" }}>
          {quoteData.map((quote, index) => {
            const isSelected = formData.quote?.id === quote.id;

            return (
              <Card
                key={index}
                style={{
                  width: "100%",
                  border: isSelected
                    ? "2px solid #1890ff"
                    : "1px solid #d9d9d9",
                  boxShadow: isSelected
                    ? "0 0 0 2px rgba(24, 144, 255, 0.2)"
                    : "none",
                  cursor: "pointer",
                }}
                bodyStyle={{ padding: "16px" }}
                onClick={() => handleSelectQuote(quote)}
              >
                <Row gutter={16} align="middle">
                  <Col span={12}>
                    <Text
                      style={{ fontSize: 20 }}
                      type={isSelected ? "success" : "secondary"}
                    >
                      {quote.provider}
                    </Text>
                  </Col>
                  <Col span={12} style={{ textAlign: "right" }}>
                    <Text
                      strong
                      style={{ fontSize: 20 }}
                      type={isSelected ? "success" : "secondary"}
                    >
                      ${quote.price}
                    </Text>
                  </Col>
                </Row>

                <Row gutter={16} style={{ marginTop: 8 }}>
                  <Col span={12}>
                    <Text type="secondary">
                      {intl.formatMessage({
                        id: "pages.quotation.estimatedPickup",
                      })}
                      : {formatDate(quote.estimatedPickupDate)}
                    </Text>
                  </Col>
                  <Col span={12}>
                    <Text type="secondary">
                      {intl.formatMessage({
                        id: "pages.quotation.estimatedDelivery",
                      })}
                      : {formatDate(quote.estimatedDeliveryDate)}
                    </Text>
                  </Col>
                </Row>

                {quote.serviceType && (
                  <Row style={{ marginTop: 8 }}>
                    <Col span={24}>
                      <Text type="secondary">
                        {intl.formatMessage({
                          id: "pages.quotation.serviceType",
                        })}
                        : {quote.serviceType}
                      </Text>
                    </Col>
                  </Row>
                )}
              </Card>
            );
          })}

          {quoteData.length === 0 && !loading && (
            <Card>
              <Text type="secondary">
                {intl.formatMessage({ id: "pages.quotation.noData" })}
              </Text>
            </Card>
          )}
          {formDataChanged && (
            <div style={{ textAlign: "center", marginTop: 16 }}>
              <Button
                type="primary"
                onClick={handleRefreshQuotation}
                style={{ width: "100%", height: "48px" }}
                loading={loading}
              >
                {intl.formatMessage({ id: "pages.quotation.refreshButton" })}
              </Button>
            </div>
          )}
        </Space>
      </Card>
    </div>
  );
};

export default QuoteInfo;